<template>
  <div class="chart-container">
    <slot></slot>
    <div ref="chartRef" class="chart-content"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts/core';
import 'echarts-wordcloud'; // 引入词云图扩展
import { TooltipComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([TooltipComponent, CanvasRenderer]);

const chartRef = ref(null);
let chartInstance = null;

const option = ref({ // 词云 Option (Copied from Home.vue)
  tooltip: {
    show: true, backgroundColor: 'rgba(0, 10, 30, 0.8)', borderColor: '#0ff',
    textStyle: { color: '#fff' }, formatter: '{b} : {c}'
  },
  series: [{
    type: "wordCloud", shape: "circle", keepAspect: false,
    left: "center", top: "center", width: "95%", height: "95%",
    sizeRange: [12, 55], rotationRange: [-45, 45], rotationStep: 45,
    gridSize: 12, drawOutOfBound: false, layoutAnimation: true,
    textStyle: {
      color: function () {
        const colors = ['#00FFFF', '#7FFFD4', '#40E0D0', '#AFEEEE', '#00E5EE', '#B0E0E6'];
        return colors[Math.floor(Math.random() * colors.length)];
      }
    },
    emphasis: {
      textStyle: { color: '#fff', textShadowBlur: 5, textShadowColor: "rgba(0, 198, 255, 0.8)", }
    },
    data: [],
  }]
});

const initChart = async () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  try {
    const response = await axios.get('/api/word_frequency');
    if (response.data.code === 200) {
        option.value.series[0].data = response.data.data;
        chartInstance.setOption(option.value);
    } else {
        console.error("Chart5 Error:", response.data.msg);
    }
  } catch (error) {
    console.error("Chart5 Network Error:", error);
  }
};

const resizeHandler = () => {
  chartInstance?.resize();
};

onMounted(async () => {
  await nextTick();
  initChart();
  window.addEventListener('resize', resizeHandler);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler);
  chartInstance?.dispose();
});
</script>

<style scoped>
.chart-container { width: 100%; height: 100%; display: flex; flex-direction: column; }
.chart-content { flex-grow: 1; width: 100%; height: 100%; }
</style>